﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Common.Services;
using FredCK.FCKeditorV2;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Eneta.Portal.NewsAndBlogs.Controls
{
    public class AnnouncementEditorControl : UserControl
    {
        protected Button saveButton;
        protected HtmlGenericControl messageBox;
        protected Label messageLabel;

        protected TextBox titleField;
        protected FCKeditor shortDescriptionField;
        protected HtmlGenericControl companiesContainer;
        protected DropDownList companiesDropDown;

        private AnnouncementDto _item;

        protected AnnouncementDto Item
        {
            get
            {
                if (_item != null)
                    return _item;

                var id = Helper.GetIdFromQueryString(Request.QueryString["aid"]);
                if (id == 0)
                    return null;

                var rep = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);
                _item = rep.GetAnnouncementById(id);
                return _item;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            saveButton.Click += SaveButtonClick;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var redirectUrl = "/_layouts/Eneta.Portal.Authentication/LiveAuthHandler.aspx?action=login";
            redirectUrl += "&ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.PathAndQuery);
            
            var currentUser = SPContext.Current.Web.CurrentUser;
            if (currentUser == null)
            {
                Response.Redirect(redirectUrl, false);
                return;
            }

            if (Item != null)
            {
                if (string.IsNullOrEmpty(Item.OwnerUserName))
                {
                    Response.Redirect(redirectUrl);
                    return;
                }

                if (Item.OwnerUserName != currentUser.LoginName)
                    if (!currentUser.IsSiteAdmin)
                    {
                        Response.Redirect("/");
                        return;
                    }
            }

            messageBox.Visible = false;
            messageLabel.Text = string.Empty;

            companiesContainer.Visible = EnetaApplication.BindCompaniesToArticles;

            if (IsPostBack)
                return;

            if(companiesContainer.Visible)
                BindCompanies();

            if (Item == null)
                return;

            titleField.Text = Item.Title;
            shortDescriptionField.Value = Item.Body;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            Page.RegisterClientScriptBlock("descrField", "<script>var descrFieldId='" + shortDescriptionField.ClientID + "';</script>");
            messageBox.Visible = !string.IsNullOrEmpty(messageLabel.Text);
            SetCheckStyles(Controls);
        }

        private static void SetCheckStyles(ControlCollection controls)
        {
            foreach (Control c in controls)
                if (c.GetType() == typeof(CheckBox))
                    ((CheckBox)c).InputAttributes["class"] = "choice";
                else if (c.HasControls())
                    SetCheckStyles(c.Controls);

        }

        protected void SaveButtonClick(object sender, EventArgs e)
        {
            string operation;
            if (SPContext.Current.Web.CurrentUser == null)
            {
                Response.Redirect("/", false);
                return;
            }

            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var profile = profileRepository.GetUserProfileByUserName(SPContext.Current.Web.CurrentUser.LoginName);


            var name = titleField.Text;

            var errors = new Dictionary<string, string>();

            if (string.IsNullOrEmpty(name))
            {
                errors.Add("title", GetResourceString("AnnouncementTitleCannotBeEmpty"));
            }
            else if (name.Length > 255)
            {
                errors.Add("title", GetResourceString("AnnouncementTitleTooLong"));
            }
            
            if (string.IsNullOrEmpty(shortDescriptionField.Value))
            {
                errors.Add("shortDescription", GetResourceString("AnnouncementDescriptionCannotBeEmpty"));
            }

            if (errors.Count > 0)
            {
                ApplyErrors(errors);
                return;
            }

            Logger.LogInfo("SaveButtonClick(): adding approver role to user");
            //AddApproverRoleToUser();

            SPSecurity.CatchAccessDeniedException = false;

            //try
            //{
                if (Item == null)
                {
                    operation = "annsave";
                }
                else
                {
                    operation = "annedit";
                }

                var repository = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);
                var dto = new AnnouncementDto();
                if (Item == null)
                    dto.Id = 0;
                else
                    dto.Id = Item.Id;
                dto.Title = titleField.Text;
                dto.Body = shortDescriptionField.Value;
                dto.OwnerUserName = SPContext.Current.Web.CurrentUser.LoginName;

                repository.SaveAnnouncement(dto);            
            //}
            //catch (Exception ex)
            //{
            //    Logger.LogException(ex);
            //    messageLabel.Text = "Teate salvestamine ebaõnnestus tehnilistel põhjustel";
            //    //RemoveApproverRoleFromUser();
            //    return;
            //}

            //RemoveApproverRoleFromUser();

            if (Item == null)
            {
                try
                {
                    var currentUser = SPContext.Current.Web.CurrentUser;
                    var mailer = new MailerService();
                    var addresses = new[] { profile.Email, "abi@eneta.ee" };
                    mailer.SendMailByTemplate("AnnouncementAdded", currentUser.Name, titleField.Text, null, addresses);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                }
            }

            int userId;
            if (IsCurrentUser(out userId))
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profile.Id + "&msg=" + operation, false);
            else
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + userId + "&msg=" + operation, false);
        }

        private bool IsCurrentUser(out int userId)
        {
            string owner = Request.QueryString["Owner"];
            if (string.IsNullOrEmpty(owner))
            {
                userId = -1;
                return true;
            }
            int ownerId;
            if (!int.TryParse(owner, out ownerId))
            {
                userId = -1;
                return true;
            }
            userId = ownerId;
            return false;
        }

        private void SavePage()
        {           
            //
            //                  Firmade osa on siit vajalik!!!!
            //
            //
            //var siteId = SPContext.Current.Site.ID;
            //var userId = SPContext.Current.Web.CurrentUser.LoginName;

            //using (var site = new SPSite(siteId))
            //{
            //    using (var web = site.OpenWeb("/uudised/teated/"))
            //    {


            //        //if (!string.IsNullOrEmpty(companiesDropDown.SelectedValue))
            //        //{
            //        //    var companiesValue = new SPFieldLookupValueCollection();
            //        //    var companyRepository = new CompanyRepository(SPContext.Current.Web);                        
            //        //    var companyId = int.Parse(companiesDropDown.SelectedValue);
            //        //    var company = companyRepository.GetCompanyById(companyId);
            //        //    var companyValue = new SPFieldLookupValue(
            //        //                                company.Id,
            //        //                                company.Title
            //        //                            );
            //        //    companiesValue.Add(companyValue);

            //        //    fieldId = item.Fields.GetFieldByInternalName("Companies").Id;
            //        //    item[fieldId] = companiesValue;
            //        //}
            //        //else
            //        //{
            //        //    fieldId = item.Fields.GetFieldByInternalName("Companies").Id;
            //        //    item[fieldId] = null;
            //        //}

            //        //item.Update();
            //        //item.File.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
            //        //item.File.Update();
            //    }
            //}
            //});
            //SPSecurity.RunWithElevatedPrivileges(sec);
            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var profile = profileRepository.GetUserProfileByUserName(SPContext.Current.Web.CurrentUser.LoginName);
            Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profile.Id + "&msg=annsave", false);
        }


        private void ApplyErrors(Dictionary<string, string> errors)
        {
            foreach (var fieldKey in errors.Keys)
            {
                var error = errors[fieldKey];
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "Container<br>");
                    //Response.End();
                }
                else
                    ctl.Attributes.Add("class", "info-row failed-info");

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorMessage<br>");
                    //Response.End();
                }
                else
                    ctl.Visible = true;

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorLabel<br>");
                    //Response.End();
                }
                else
                    ctl.InnerText = error;

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorNote", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorNote<br>");
                    //Response.End();
                }
                else
                    ctl.Visible = true;
            }
        }

        private void BindCompanies()
        {
            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            var companies = repository.GetApprovedCompanies();

            companiesDropDown.DataSource = companies.OrderBy(c => c.Title);
            companiesDropDown.DataBind();

            companiesDropDown.Items.Insert(0, new ListItem("- " + GetResourceString("None") + " -", string.Empty));

            if (Item == null)
                return;

            if (Item.Companies == null)
                return;

            if (Item.Companies.Count > 0)
            {
                var company = Item.Companies[0];
                if (company != null)
                    if (companiesDropDown.Items.FindByValue(company.Id.ToString()) != null)
                        companiesDropDown.SelectedValue = company.Id.ToString();
            }
        }
        private static string GetResourceString(string label)
        {
            var resourceString = "$Resources:NewsAndBlogs," + label;
            var result = SPUtility.GetLocalizedString(resourceString, "NewsAndBlogs", SPContext.Current.Web.Language);
            return result;
        }
    }
}
